package plugin

import (
	"gitee.com/mkwchecking/k-scaffold/config"
	"gitee.com/mkwchecking/k-scaffold/pkg/rely/casbin"
	ocasbin "github.com/casbin/casbin/v2"
)

var _casbin *ocasbin.Enforcer

func (p *Plugins) GetCasbin() (*ocasbin.Enforcer, error) {
	if _casbin != nil {
		return _casbin, nil
	}

	log, err := p.GetLogger()
	if err != nil {
		return nil, err
	}

	appConf := config.Get().App
	casbinConf, err := config.GetHTTPCasbin()
	if err != nil {
		return nil, err
	}

	dbconf, err := config.GetDefaultDatabase()
	if err != nil {
		return nil, err
	}

	gdb, err := p.GetGdb()
	if err != nil {
		return nil, err
	}

	sqldb, err := p.GetSqlDB()
	if err != nil {
		return nil, err
	}

	enforce, err := casbin.New(appConf.Env, casbinConf, dbconf.DatabaseConn, log.Logger, gdb, sqldb)
	if err != nil {
		return nil, err
	}

	_casbin = enforce
	return _casbin, nil
}
